<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb5">
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cms:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['cms:goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['cms:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['cms:goods:export']"
        >导出</el-button>
      </el-col>
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" class="el-form-search">
                         <el-form-item label="是否下载" prop="downStatus" class="el-form-search-item">
                          <el-select v-model="queryParams.downStatus" placeholder="请选择">
                            <el-option
                            v-for="item in optionsItem"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                          </el-select>
                        </el-form-item>
                          <el-form-item label="视频名称" prop="goodsName" class="el-form-search-item">
                            <el-input
                                    v-model="queryParams.goodsName"
                                    placeholder="请输入视频名称"
                                    clearable
                                    size="mini"
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="添加时间" prop="createDate" class="el-form-search-item">
                            <el-date-picker clearable size="mini"
                                            v-model="queryParams.createDate"
                                            type="date"
                                            value-format="yyyy-MM-dd"
                                            placeholder="选择添加时间">
                            </el-date-picker>
                        </el-form-item>
            <el-form-item class="el-form-search-item">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
    </el-row>

    <el-table :height="tableHeight" v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center">
            <template scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
            </template>
        </el-table-column>
      <el-table-column label="视频名称" align="center" prop="goodsName" />
      <el-table-column label="是否热门" align="center" prop="isHot" :formatter="yesOrNoFormat"/>
      <el-table-column label="是否下载" align="center" prop="downStatus" :formatter="yesOrNoFormat"/>
      <el-table-column label="商品类型" align="center" prop="goodsType" :formatter="stateFormat"/>
      <el-table-column label="一级分类" align="center" prop="catetoryId" :formatter="categoryFormat"/>
      <el-table-column label="二级分类" align="center" prop="categoryTwoId"  :formatter="categoryFormat"/>
      <el-table-column label="用户等级" align="center" prop="userLevel"/>
      <el-table-column label="视频图片" align="center" prop="goodsImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.goodsImage" :width="30" :height="30"/>
        </template>
      </el-table-column>
      <el-table-column label="视频地址" align="center" prop="goodsVideo" >
      </el-table-column>
      <el-table-column label="所需积分" align="center" prop="goodsIntegral" />
      <!-- <el-table-column label="商品描述" align="center" prop="goodsDesc" /> -->
      <el-table-column label="商品排序" align="center" prop="goodsSort" />
      <el-table-column label="上架状态" align="center" prop="goodsStatus" :formatter="goodsStateFormat"/>
      <el-table-column label="添加时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cms:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['cms:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改视频管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false" v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="视频名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入视频名称" />
        </el-form-item>
        <el-form-item label="一级分类" prop="catetoryId">
          <!-- <el-input v-model="form.catetoryId" placeholder="请输入一级分类ID" /> -->
          <treeselect
            v-model="form.catetoryId"
            @select="departTreeSelected"
            :options="categoryOptions"
            :normalizer="normalizer"
            :default-expand-level="1"
            placeholder="请选择分类"
          />
        </el-form-item>
        <el-form-item label="二级分类" prop="categoryTwoId">
          <!-- <el-input v-model="form.categoryTwoId" placeholder="请输入二级分类ID" /> -->
          <treeselect
            v-model="form.categoryTwoId"
            :options="categoryOptions1"
            :normalizer="normalizer"
            :default-expand-level="1"
            placeholder="请选择分类"
          />
        </el-form-item>
        <el-form-item label="是否热门" prop="isHot">
          <el-radio-group v-model="form.isHot">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="是否下载" prop="downStatus">
          <el-radio-group v-model="form.downStatus">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="商品类型" prop="goodsType">
          <el-radio-group v-model="form.goodsType">
            <el-radio :label="1">视频</el-radio>
            <el-radio :label="2">文案</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="视频图片" v-if="form.goodsType==1">
          <image-upload v-model="form.goodsImage"/>
        </el-form-item>
        <el-form-item label="视频地址"  v-if="form.goodsType==1">
        <!-- <file-upload v-model="form.goodsVideo"
          :fileType="['mp4']"
          :fileSize=200
          :isMultiple="true"
          /> -->
         <FileUpload1  v-model="form.goodsVideo"/>
          <!-- <el-progress :percentage="progress" status="success"></el-progress> -->
        </el-form-item>
        <el-form-item label="视频积分" prop="goodsIntegral" v-if="form.goodsType==1">
          <el-input v-model="form.goodsIntegral" placeholder="请输入视频需要积分" />
        </el-form-item>
        <el-form-item label="用户等级" prop="userLevel">
          <el-input v-model="form.userLevel" placeholder="请输入用户等级" />
        </el-form-item>
        <el-form-item label="商品描述" prop="goodsDesc" >
          <!-- <editor v-model="form.goodsDesc" :min-height="192"/> -->
          <el-input v-model="form.goodsDesc" type="textarea" placeholder="请输入商品描述"
            :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="goodsStatus">
          <el-radio-group v-model="form.goodsStatus">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="商品排序" prop="goodsSort">
          <el-input v-model="form.goodsSort" placeholder="请输入商品排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FileUpload1 from "@/components/FileUpload1";

import { listCategory } from "@/api/cms/category";
import { listGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/cms/goods";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Goods",
  components: {
    Treeselect,FileUpload1
  },
  data() {
    return {
      optionsItem: [{
          value: '0',
          label: '否'
        }, {
          value: '1',
          label: '是'
        }],
      // 表格高度
      tableHeight: document.documentElement.clientHeight - 180,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频管理表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        delStatus: 0,
        orderByColumn: "create_date",
        isAsc: "desc",
        goodsName: null,
        goodsStatus: null,
        createDate: null
      },
      treeParams:{categoryPid:0},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: '视频名称不能为空', trigger: 'blur' }
        ],
        catetoryId: [
          { required: true, message: '请选择一级分类', trigger: 'blur' }
        ],
        categoryTwoId: [
          { required: true, message: '请选择二级分类', trigger: 'blur' }
        ]
      },
      categoryOptions:[],
      categoryOptions1:[],
      categoryList:[],
      files:[],
      progress:0
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询视频管理列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listCategory().then(response=>{
        this.categoryList = response.data;
        console.log(this.categoryList)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        goodsType: 1,
        catetoryId: null,
        categoryTwoId: null,
        goodsImage: null,
        goodsVideo: null,
        goodsVideo5: null,
        goodsIntegral: 50,
        goodsDesc: null,
        goodsSort: null,
        goodsStatus: 1,
        delStatus: 0,
        userLevel: 1,
        isHot: 0,
        createDate: null
      };
      this.resetForm("form");
    },
     /** 查询分类管理下拉树结构 */
     getTreeselect() {
      this.treeParams.categoryPid=0;
      listCategory(this.treeParams).then((response) => {
        this.categoryOptions = [];
        const data = { id: 0, classifyName: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.categoryOptions.push(data);
      });
    },
    getTreeselect1(id) {
      this.treeParams.categoryPid=id;
      listCategory(this.treeParams).then((response) => {
        this.categoryOptions1 = [];
        const data = { id: 0, classifyName: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.categoryOptions1.push(data);
      });
    },
    /** 转换分类管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children,
      };
    },
    departTreeSelected(node,instancdId){
      this.form.categoryTwoId = null;
      this.getTreeselect1(node.id)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      this.open = true;
      this.title = "添加视频";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.getTreeselect1(row.catetoryId)
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改视频";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form)
          if (this.form.goodsVideo == null){
            this.$modal.msgError("请上传视频或等待视频上传完成");
            return
          }
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除记录？').then(function() {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cms/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    },
    stateFormat(row,column){
      if(row.goodsType==1){
        return "视频"
      }else if(row.goodsType==2){
        return "文案"
      }
    },
    yesOrNoFormat(row,column){
      if(row[column.property]==1){
        return "是"
      }else if(row[column.property]==0){
        return "否"
      }
    },
    goodsStateFormat(row,column){
      if(row.goodsStatus==0){
        return "下架"
      }else if(row.goodsStatus==1){
        return "上架"
      }
    },
    categoryFormat(row,column){
      for(let i=0;i<this.categoryList.length;i++){
        let obj =  this.categoryList[i];
        if(obj.id==row[column.property]){
          return obj.categoryName;
        }
      }
    }
  }
};
</script>
